package com.meritdata.cloud.data.service.development.service;

import com.meritdata.cloud.data.service.development.model.QTdDataApiParameter;
import com.meritdata.cloud.data.service.development.model.TdDataApiParameter;
import com.meritdata.cloud.data.service.development.repository.IDataApiParameterDao;
import com.querydsl.core.types.Predicate;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class DataApiParameterService {
    @Autowired
    private JPAQueryFactory jpaQueryFactory;

    @Autowired
    private IDataApiParameterDao iDataApiParameterDao;

    public void add(TdDataApiParameter category) {
        iDataApiParameterDao.save(category);
    }


    public boolean save(TdDataApiParameter category) {
        Date now = new Date();
        category.setUpdateTime(now);
        iDataApiParameterDao.save(category);
        return true;
    }

    public Optional<TdDataApiParameter> get(String id) {
        return iDataApiParameterDao.findById(Long.valueOf(id));
    }

    public boolean delete(String id) {
        iDataApiParameterDao.deleteById(Long.valueOf(id));
        return true;
    }
    @Modifying
    public boolean udpate(String id,String name,String code,String type,String defaultVal,Date updateTime) {
        return iDataApiParameterDao.update(Long.valueOf(id),name,code,type,defaultVal,updateTime) >=0;
    }

    public List<TdDataApiParameter> tree(Long apiId) {
        QTdDataApiParameter qTdDataApiParameter = QTdDataApiParameter.tdDataApiParameter;
        Predicate predicate =qTdDataApiParameter.apiId.eq(apiId);
        return jpaQueryFactory.selectFrom(qTdDataApiParameter)
                .where(predicate)
                .orderBy(qTdDataApiParameter.updateTime.desc())
                .fetch();
    }

}
